package com.cloud.freeflow.api.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.freeflow.api.entity.ProcActDef;
import com.cloud.freeflow.api.entity.ProcActPart;
import com.cloud.freeflow.api.entity.ProcPart;
import com.cloud.freeflow.api.mapper.ProcActDefMapper;
import com.cloud.freeflow.api.mapper.ProcActPartMapper;
import com.cloud.freeflow.api.mapper.ProcPartMapper;
import com.cloud.freeflow.api.service.ProcPartService;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class ProcPartServiceImpl implements ProcPartService {

	@Autowired
	private ProcActDefMapper procActDefMapper;

	@Autowired
	private ProcPartMapper procPartMapper;

	@Autowired
	private ProcActPartMapper procActPartMapper;

	@Override
	public List<ProcPart> listProcParts(long id) {
		Example example = new Example(ProcPart.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("procDefId", id);
		return procPartMapper.selectByExample(example);
	}

	@Override
	public List<ProcPart> addParts(List<ProcPart> procParts) {
		List<ProcPart> ps = new ArrayList<ProcPart>();
		for (ProcPart part : procParts) {
			if (!procPartMapper.existsWithPrimaryKey(part)) {
				procPartMapper.insert(part);
				ps.add(part);
			}
		}
		return ps;
	}

	@Override
	public long deleteParts(ProcPart part) {
		procPartMapper.deleteByPrimaryKey(part);
		return part.getPartId();
	}

	@Override
	public List<ProcPart> listActParts(Long actDefId) {
		ProcActDef procActDef = procActDefMapper.selectByPrimaryKey(actDefId);
		return procActPartMapper.listActParts(procActDef.getProcDefId(), actDefId);
	}

	@Override
	public void saveActParts(Long actDefId, String partIds) {
		Example exp = new Example(ProcActPart.class);
		Example.Criteria criteria = exp.createCriteria();
		criteria.andEqualTo("actDefId", actDefId);
		procActPartMapper.deleteByExample(exp);
		if (StringUtils.isNotEmpty(partIds)) {
			String[] ids = partIds.split(",");
			for (String id : ids) {
				ProcActPart aPart = new ProcActPart();
				aPart.setActDefId(actDefId);
				aPart.setPartId(Long.valueOf(id));
				procActPartMapper.insert(aPart);
			}
		}
	}

	@Override
	public List<ProcPart> listActSelectedParts(Long actDefId) {
		ProcActDef procActDef = procActDefMapper.selectByPrimaryKey(actDefId);
		return procActPartMapper.listActSelectedParts(procActDef.getProcDefId(), actDefId);
	}

}
